package dao.impl;

import dao.IStudentDao;
import pojo.Student;
import util.DBConn;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements IStudentDao {
    private Connection conn;
    private Statement stmt;
    private ResultSet rs;
    String url = "jdbc:mysql://localhost:3306/javaeelab";
    public Student findStudentByNum(String num){
        Student student=null;
        try {
            //1. 创建连接对象
            conn= DBConn.getConnection(url);
            //3.创建命令对象
            stmt=conn.createStatement();
            //4.执行SQL语句  2040706301-雷诏华
            String sql = "SELECT * FROM tb_student where num='"+num+"'";
            rs=stmt.executeQuery(sql);
            if(rs.next()) {
                student=new Student();
                student.setNum(rs.getString("num"));
                student.setName(rs.getString("name"));
                student.setGender(rs.getString("gender"));
                student.setMajor(rs.getString("major"));
            }

            conn.close();
            rs.close();
            stmt.close();
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return student;
    }

    public List<Student> findStudentsByName(String name){
        List<Student> students=null;
        try {
            //1. 创建连接对象
            conn= DBConn.getConnection(url);
            //3.创建命令对象
            stmt=conn.createStatement();
            //4.执行SQL语句
            String sql = "SELECT * FROM tb_student where name like '%"+name+"%'";
            rs=stmt.executeQuery(sql);
            students=new ArrayList<>();
            while (rs.next()) {
                Student student=new Student();
                student.setNum(rs.getString("num"));
                student.setName(rs.getString("name"));
                student.setGender(rs.getString("gender"));
                student.setMajor(rs.getString("major"));
                students.add(student);
            }
            conn.close();
            rs.close();
            stmt.close();
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return students;
    }

    public static void main(String[] args) {
        StudentDaoImpl dao=new StudentDaoImpl();
        System.out.println(dao.findStudentByNum("0001"));
        List<Student> students=dao.findStudentsByName("斌");
        for (Student student:students){
            System.out.println(student);
        }
    }
}
